<template>
  <div class="app-container">
    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="品牌名称:" prop="brandName">
          <el-input v-model="queryParams.brandName" clearable placeholder="请输入品牌名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车系名称:" prop="seriesName">
          <el-input v-model="queryParams.seriesName" clearable placeholder="请输入车系名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车型名称:" prop="modelName">
          <el-input v-model="queryParams.modelName" clearable placeholder="请输入车型名称"></el-input>
        </el-form-item>
      </el-col>
    </SearchContent>

    <div class="card-wrap paddingAll20" :model="queryParams" ref="queryForm" label-width="86px">
      <div class="table-title-wrap justify-end">
        <el-button type="primary" @click="handleAdd" v-hasPermi="['vehicleModelList:vehicleModelList:add']">新增
        </el-button>
        <!--        <el-button type="info" @click="handleImport"-->
        <!--                   v-hasPermi="['vehicleModelList:vehicleModelList:import']">导入-->
        <!--        </el-button>-->
        <!--        <el-button type="warning" @click="handleExport"-->
        <!--                   v-hasPermi="['vehicleModelList:vehicleModelList:derive']">导出-->
        <!--        </el-button>-->
      </div>
      <table-page :loading="loading" :dataList="dataList" :total="total" border :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @setSizeCurrent="getList">
        <template slot="tableColAc">
          <el-table-column label="操作" align="center" fixed="left" width="180">
            <template slot-scope="scope">
              <!--  -->
              <el-button size="mini" type="text" v-hasPermi="['vehicleModelList:vehicleModelList:vehicleMapping']"
                         @click="vehicleMapping(scope.row)">车型映射
              </el-button>
              <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                         v-hasPermi="['vehicleModelList:vehicleModelList:edit']">编辑
              </el-button>
              <el-button size="mini" type="text" @click="viewOpen(scope.row)"
                         v-hasPermi="['vehicleModelList:vehicleModelList:view']">查看
              </el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                         v-if="scope.row.isAvailable == '0'" v-hasPermi="['vehicleModelList:vehicleModelList:dele']">删除
              </el-button>
              <el-button size="mini" type="text" @click="handleAc(scope.row, 1)"
                         v-if="scope.row.isAvailable == '0'" v-hasPermi="['vehicleModelList:vehicleModelList:enable']">
                启用
              </el-button>
              <el-button size="mini" type="text" @click="handleAc(scope.row, 0)"
                         v-if="scope.row.isAvailable == '1'" v-hasPermi="['vehicleModelList:vehicleModelList:service']">
                停用
              </el-button>
            </template>
          </el-table-column>

        </template>

        <template slot="tableCol">
          <el-table-column label="品牌" align="center" prop="brandName" min-width="120" show-overflow-tooltip/>
          <el-table-column label="车系" align="center" prop="seriesName" min-width="180"/>
          <el-table-column label="车型" align="center" prop="modelName" min-width="260" show-overflow-tooltip/>
          <el-table-column label="车系组" align="center" prop="seriesGroupName" min-width="180"/>
          <el-table-column label="查博士车型" align="center" min-width="260" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.cbsBrandName }}{{ scope.row.cbsSeriesName }}{{ scope.row.cbsModelName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="150">
            <template slot-scope="scope">
              <el-tag type="success" v-show="scope.row.isAvailable == '1'">已启用</el-tag>
              <el-tag type="danger" v-show="scope.row.isAvailable == '0'">停用</el-tag>
            </template>
          </el-table-column>
        </template>
      </table-page>
    </div>

    <!-- 添加或修改测试单表对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body class="form-dialog" width="95%">
      <el-form ref="form" :model="form" label-width="118px">

        <el-card shadow="never" class="box-card">

          <div class="card-title" slot="header">基本信息</div>
          <el-row :gutter="16">
            <el-col :span="6">

              <el-form-item label="品牌名称:" prop="brandId"
                            :rules="{required:true,message:'请选择品牌名称',trigger:'change'}">

                <el-select v-model="form.brandId" filterable placeholder="请选择品牌名称" clearable
                           @change="changeBrand" v-if="isNew" style="width: 100%;">
                  <el-option v-for="item in getBrandNameList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
                <span v-else>{{ form.brandName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车系名称:" prop="seriesId"
                            :rules="{required:true,message:'请选择车系名称',trigger:'change'}">
                <el-select v-model="form.seriesId" filterable placeholder="请选择车系名称" clearable
                           @change="changeSeries" v-if="isNew" style="width: 100%;">
                  <el-option v-for="item in getSeriesNameList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
                <span v-else>{{ form.seriesName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="车型名称:" prop="modelName"
                            :rules="{required:true,message:'请输入车型名称',trigger:'blur'}">
                <el-input v-model="form.modelName" maxlength="100" clearable placeholder="请输入车型名称"
                          v-if="isNew"></el-input>

                <span v-else>{{ form.modelName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="车系组名称:" prop="seriesGroupId">
                <el-select v-model="form.seriesGroupId" filterable placeholder="请选择车系组名称" clearable
                           @change="changeSeriesGroup" v-if="isNew" style="width: 100%;">
                  <el-option v-for="item in seriesGroupList" :key="item.id" :label="item.seriesGroupName"
                             :value="item.id">
                  </el-option>
                </el-select>
                <span v-else>{{ form.seriesGroupName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="车型短名:" prop="shortName">
                <el-input v-model="form.shortName" clearable placeholder="请输入车型短名" v-if="isNew"></el-input>
                <span v-else>{{ form.shortName }}</span>

              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="年份:" prop="year">
                <el-date-picker value-format="yyyy" v-model="form.year" type="year" placeholder="请选择年份"
                                v-if="isNew" style="width: 100%;">
                </el-date-picker>
                <span v-else>{{ form.year }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="价格(万元):" prop="price"
                            :rules="{required:true,message:'请输入价格(万元):',trigger:'blur'}">
                <el-input v-model="form.price" clearable placeholder="请输入价格(万元)" v-if="isNew"
                          @change="handleChange('price','float')"
                          v-thousand/>
                <span v-else>{{ form.price }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- <el-form-item label="是否启用:" prop="isAvailable">
                <el-radio-group v-model="form.isAvailable" v-if="isNew">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
                <span v-else>{{ form.isAvailable  == 1? '启用' : '停用'  }}</span>
              </el-form-item> -->
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" class="box-card">
          <div class="card-title" slot="header">车型参数信息</div>
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="排量:" prop="liter" :rules="{required:true,message:'请输入排量',trigger:'blur'}">
                <el-input v-model="form.liter" clearable @change="handleChange('liter','float')"
                          placeholder="请输入排量" v-if="isNew"></el-input>
                <span v-else>{{ form.liter }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="排放标准:" prop="dischargeStandard">
                <el-input v-model="form.dischargeStandard" clearable placeholder="请输入排放标准"
                          v-if="isNew"></el-input>
                <span v-else>{{ form.dischargeStandard }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="燃料类型名称:" prop="fuelTypeId"
                            :rules="{required:true,message:'请选择燃料类型名称',trigger:'change'}">
                <el-select v-model="form.fuelTypeId" placeholder="请选择燃料类型名称" clearable v-if="isNew"
                           @change="changeFuelType" style="width: 100%;">
                  <el-option v-for="item in fuelTypeList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                <span v-else>{{ form.fuelTypeName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="马力:" prop="enginePower">
                <el-input v-model="form.enginePower" clearable @change="handleChange('enginePower','int')"
                          placeholder="请输入马力" v-if="isNew"></el-input>
                <span v-else>{{ form.enginePower }}</span>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="功率:" prop="enginePowerKw">
                <el-input v-model="form.enginePowerKw" clearable @change="handleChange('enginePowerKw','int')"
                          placeholder="请输入功率" v-if="isNew"></el-input>
                <span v-else>{{ form.enginePowerKw }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否新能源:" prop="isGreen"
                            :rules="{required: true, message: '请选择是否新能源', trigger: 'change'}">
                <el-radio-group v-model="form.isGreen" v-if="isNew">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">不是</el-radio>
                </el-radio-group>
                <span v-else>{{ form.isGreen != null ? form.isGreen == 1 ? '是' : '不是' : '' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="公告号:" prop="modelCode">
                <el-input v-model="form.modelCode" clearable placeholder="请输入公告号" v-if="isNew"></el-input>
                <span v-else>{{ form.modelCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="驱动名称:" prop="driveName">
                <el-input v-model="form.driveName" clearable placeholder="请输入驱动名称" v-if="isNew"></el-input>
                <span v-else>{{ form.modelCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="驱动类型:" prop="driveType">
                <el-input v-model="form.driveType" clearable placeholder="请输入驱动类型" v-if="isNew"></el-input>
                <span v-else>{{ form.driveType }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车型状态:" prop="modelStatus">
                <el-input v-model="form.modelStatus" clearable placeholder="请输入车型状态" v-if="isNew"></el-input>
                <span v-else>{{ form.modelStatus }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="变速类型:" prop="gearType">
                <el-input v-model="form.gearType" clearable placeholder="请输入变速类型" v-if="isNew"></el-input>
                <span v-else>{{ form.gearType }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="变速箱名称:" prop="gearName">
                <el-input v-model="form.gearName" clearable placeholder="请输入变速箱名称" v-if="isNew"></el-input>
                <span v-else>{{ form.gearName }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="新能源类型:" prop="greenTypeId">
                <el-select v-model="form.greenTypeId" placeholder="请选择新能源类型" clearable v-if="isNew"
                           style="width: 100%;" @change="changeGreenType">
                  <el-option v-for="item in greenTypeList" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
                <span v-else>{{ form.greenTypeName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="上市日期:" prop="marketDate">
                <el-date-picker v-if="isNew" v-model="form.marketDate" value-format="yyyy-MM-dd" type="date"
                                style="width: 100%;" placeholder="请选择上市日期">
                </el-date-picker>

                <span v-else>{{ form.marketDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="最小上牌年份:" prop="minRegYear">
                <el-date-picker v-model="form.minRegYear" type="year" value-format="yyyy"
                                placeholder="请选择最小上牌年份" v-if="isNew" style="width: 100%;">
                </el-date-picker>
                <span v-else>{{ form.minRegYear }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="最大上牌年份:" prop="maxRegYear">
                <el-date-picker v-model="form.maxRegYear" value-format="yyyy" type="year"
                                placeholder="请选择最大上牌年份" v-if="isNew" style="width: 100%;">
                </el-date-picker>
                <span v-else>{{ form.maxRegYear }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="停产年份:" prop="stopMakeYear">
                <el-date-picker v-model="form.stopMakeYear" value-format="yyyy" type="year" placeholder="请选择停产年份"
                                style="width: 100%;" v-if="isNew">
                </el-date-picker>
                <span v-else>{{ form.stopMakeYear }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="进气方式:" prop="intake">
                <el-input v-model="form.intake" clearable placeholder="请输入进气方式" v-if="isNew"></el-input>
                <span v-else>{{ form.intake }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="座位数:" prop="seatNumber"
                            :rules="{required:true,message:'请输入座位数',trigger:'blur'}">
                <el-input v-model="form.seatNumber" clearable @change="handleSeatNumber" placeholder="请输入座位数"
                          v-if="isNew"></el-input>
                <span v-else>{{ form.seatNumber }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="车身类型:" prop="bodyType">
                <el-input v-model="form.bodyType" clearable placeholder="请输入车身类型" v-if="isNew"></el-input>
                <span v-else>{{ form.bodyType }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="门数:" prop="doorNumber">
                <el-input v-model="form.doorNumber" clearable @change="handleChange('doorNumber','int')"
                          placeholder="请输入门数" v-if="isNew"></el-input>
                <span v-else>{{ form.doorNumber }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车身结构:" prop="carStruct">
                <el-input v-model="form.carStruct" clearable placeholder="请输入车身结构" v-if="isNew"></el-input>
                <span v-else>{{ form.carStruct }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否平行进口:" prop="isParallel"
                            :rules="{required: true, message: '请选择是否平行进口', trigger: 'change'}">
                <el-radio-group v-model="form.isParallel" v-if="isNew">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">不是</el-radio>
                </el-radio-group>
                <span v-else>{{ form.isParallel != null ? form.isParallel == 1 ? '是' : '不是' : '' }}</span>

              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="新能源价格补贴:" prop="priceAllowance">
                <el-input v-model="form.priceAllowance" clearable
                          v-thousand
                          @change="handleChange('priceAllowance','float')" placeholder="请输入新能源价格补贴"
                          v-if="isNew"></el-input>
                <span v-else>{{ form.priceAllowance }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <e-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="isNew">确 定</e-button>
        <e-button @click="cancel">{{ isNew ? '取消' : '关闭' }}</e-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <div style="margin-bottom: 6px;">模板下载：
        <e-button size="mini" type="text" @click="handleExportT" icon="el-icon-download"
                  v-hasPermi="['demo:demo:edit']">车行列表模板
        </e-button>
      </div>

      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <e-button type="primary" @click="submitFileForm">确 定</e-button>
        <e-button @click="upload.open = false">取 消</e-button>
      </div>
    </el-dialog>

    <!-- 车型名称映射配置 -->
    <el-dialog title="车型名称映射配置" :visible.sync="MappingDig" width="40%" append-to-body>
      <div>请选择
        <span style="color: black;font-weight: 600;font-size: 15px;">{{ modelNameDig }}</span>
        在查博士系统中对应的车型名称
      </div>
      <el-form ref="form" :model="MappingDigForm" label-width="50px"
               style="padding-left: 100px;box-sizing: border-box;">
        <el-row style="margin-top: 50px;">
          <el-col :span="12">
            <el-form-item label="品牌:">
              <el-select v-model="MappingDigForm.cbsBrandId" filterable style="width:100%" @change="changeBrandList">
                <el-option v-for="item in brandList" :key="item.id" :value="item.id"
                           :label="item.brandName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车系:">
              <el-select v-model="MappingDigForm.cbsSeriesId" filterable style="width:100%"
                         @change="changeVehicleTypeList">
                <el-option v-for="item in seriesList" :key="item.id" :value="item.id" :label="item.series"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="车型:">
              <el-select v-model="MappingDigForm.cbsModelId" filterable style="width:100%"
                         @change="changeSeriesListList">
                <el-option v-for="item in vehicleTypeList" :key="item.id" :value="item.id"
                           :label="item.model"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <e-button type="primary" @click="submitMappingDig">确 定</e-button>
        <e-button @click="MappingDig = false">取 消</e-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getModelData,
  getBrandName,
  getSeriesName,
  getModelName,
  getSeriesGroupList,
  carBrandAdd,
  updateCar,
  getCarBasic,
  delModel,
  getBrandList,
  getVehicleTypeList,
  getSeriesList,
  syncCbsCarModel
} from "@/api/zcwh/vehicleModelApi";
import {getToken} from "@/utils/auth";
import SearchContent from "@/components/SearchContent/index.vue";


export default {
  name: "VehicleModelList",
  components: {
    SearchContent
  },
  data() {
    return {
      brandList: [],
      vehicleTypeList: [],
      seriesList: [],
      MappingDigForm: {
        cbsBrandName: "",
        cbsBrandId: '',
        cbsSeriesId: '',
        cbsSeriesName: '',
        cbsModelId: '',
        cbsModelName: '',
        id: ''
      },
      modelNameDig: "",
      // 车型映射配置弹窗
      MappingDig: false,
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/car/carBasic/importTemplate/importData"
      },
      isNew: true, // 新增编辑查看控制1编辑2查看
      // green_type_namelist
      greenTypeList: [
        {
          value: '0', label: '不适用'
        },
        {
          value: '1', label: '纯电动'
        },
        {
          value: '2', label: '插电式混动'
        },
        {
          value: '4', label: '增程式混动'
        },
        {
          value: '8', label: '燃料电池'
        },

      ],
      fuelTypeList: [
        {
          value: '0', label: '汽油'
        },
        {
          value: '1', label: '柴油'
        },
        {
          value: '2', label: '电力'
        },
        {
          value: '3', label: '油电'
        },
        {
          value: '4', label: '油气'
        },
        {
          value: '5', label: '天然气'
        },
        {
          value: '6', label: '氢能源'
        },
        {
          value: '7', label: '甲醇'
        },

      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandName: "",
        seriesName: "",
        modelName: "",
        styleModel: "",
        IS_AVAILABLE: "",
      },

      total: 0,
      dataList: [],
      getBrandNameList: [],
      getSeriesNameList: [],
      getModelNameList: [],
      seriesGroupList: [],

      // 表单参数
      form: {
        brandId: "",
        carBrandId: "",
        brandName: "",
        seriesName: "",
        seriesId: "",
        carSeriesId: "",
        modelId: "",
        modelName: "",
        shortName: "",
        seriesGroupName: "",
        seriesGroupId: "",
        price: "",
        year: "",
        makerId: "",
        makerName: "",

        // 车辆信息
        liter: "",
        dischargeStandard: "",
        fuelTypeId: "",
        fuelTypeName: "",
        enginePower: "",
        enginePowerKw: "",
        isGreen: "",
        modelCode: "",
        driveName: "",
        driveType: "",
        modelStatus: "",
        gearType: "",
        gearName: "",
        greenTypeId: "",
        greenTypeName: "",
        marketDate: "",
        minRegYear: "",
        maxRegYear: "",
        stopMakeYear: "",
        intake: "",
        seatNumber: "",
        bodyType: "",
        doorNumber: "",
        carStruct: "",
        isParallel: "",
        priceAllowance: "",
      },
      // 表单校验
      rules: {
        testKey: [
          {required: true, message: "key键不能为空", trigger: "blur"}
        ],
        value: [
          {required: true, message: "值不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getBrandNames()
    this.getBrandList()
  },
  methods: {
    changeBrandList() {
      this.getVehicleTypeList()
      this.MappingDigForm.cbsBrandName = this.brandList.find(v => v.id == this.MappingDigForm.cbsBrandId)?.brandName
      this.$set(this.MappingDigForm, 'cbsSeriesId', '')
      this.$set(this.MappingDigForm, 'CbsSeriesName', '')
      this.$set(this.MappingDigForm, 'cbsModelId', '')
      this.$set(this.MappingDigForm, 'CbsModelName', '')

    },
    changeVehicleTypeList() {
      this.getSeriesList()
      this.MappingDigForm.cbsSeriesName = this.seriesList.find(v => v.id == this.MappingDigForm?.cbsSeriesId)?.series
      this.$set(this.MappingDigForm, 'cbsModelId', '')
      this.$set(this.MappingDigForm, 'CbsModelName', '')
    },
    changeSeriesListList() {
      this.MappingDigForm.cbsModelName = this.vehicleTypeList.find(v => v.id == this.MappingDigForm?.cbsModelId)?.model
    },
    // 获取品牌查博士品牌
    async getBrandList() {
      try {
        let res = await getBrandList()
        this.brandList = res.data
      } catch (error) {
      }
    },
    // 获取品牌查博士车系
    async getVehicleTypeList() {
      let params = {
        brandId: this.MappingDigForm.cbsBrandId
      }
      try {
        let res = await getVehicleTypeList(params)
        this.seriesList = res.data
      } catch (error) {
      }
    },
    // 获取品牌查博士车型
    async getSeriesList() {
      let params = {
        seriesId: this.MappingDigForm.cbsSeriesId
      }
      try {
        let res = await getSeriesList(params)
        this.vehicleTypeList = res.data
      } catch (error) {
      }
    },
    // 车型映射弹窗
    vehicleMapping(row) {
      this.modelNameDig = row.modelName
      this.MappingDig = true
      if (row.cbsBrandId && row.cbsSeriesId && row.cbsModelId) {
        this.MappingDigForm.cbsBrandId = row.cbsBrandId
        this.MappingDigForm.cbsSeriesId = row.cbsSeriesId
        this.MappingDigForm.cbsModelId = row.cbsModelId
        this.getVehicleTypeList()
        this.getSeriesList()
      } else {
        this.MappingDigForm = {
          cbsBrandName: "",
          cbsBrandId: '',
          cbsSeriesId: '',
          cbsSeriesName: '',
          cbsModelId: '',
          cbsModelName: '',
          id: ''
        }
      }
      this.MappingDigForm.id = row.id
    },
    // 车型映射提交
    async submitMappingDig() {
      let data = {...this.MappingDigForm}
      try {
        let res = await syncCbsCarModel(data)
        this.$message.success('保存成功')
        this.MappingDig = false
        this.getList()
      } catch (error) {
        this.MappingDig = false
      }
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;


      getModelData(this.queryParams).then(res => {
        if (res.code == "200") {
          const {rows, total} = res
          this.dataList = rows
          this.total = total
          this.loading = false;
        }


      }).catch(() => {
        this.loading = false;
      })
    },
    handleChange(str, type) {

      if (type === 'int') {
        let msg = /^[1-9]\d*$/
        if (!msg.test(this.form[str])) {
          this.form[str] = ""
        } else {
          this.form[str] = this.form[str].toString().match(/^[1-9]\d*$/)[0]
        }
      }
      if (type === 'float') {
        let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/
        if (!msg.test(this.form[str])) {
          this.form[str] = ""
        } else {
          this.form[str] = this.form[str].toString().match(/^\d+(?:\.\d{0,2})?/)[0]
        }
      }
    },

    handleSeatNumber(val) {
      if (!val) return
      if (this.validateInput(val)) {
        this.form.seatNumber = val
      } else {
        this.form.seatNumber = ''
      }
    },

    validateInput(input) {
      const regex = /^(?:\d+|\d+\/\d+\/\d+|\d+-\d+)$/;
      if (!regex.test(input)) {
        return false;
      }
      if (input.includes('-')) {
        const [first, second] = input.split('-').map(Number);
        return first < second;
      }
      return true;
    },

    changeFuelType(val) {
      if (val) {
        if (this.fuelTypeList.length > 0) {
          let arr = this.fuelTypeList.filter(v => {
            return v.value == val
          })
          this.form.fuelTypeName = arr[0].label

        }
      } else {
        this.form.fuelTypeName = ""
      }
    },
    changeGreenType(val) {
      if (val) {
        if (this.greenTypeList.length > 0) {
          let arr = this.greenTypeList.filter(v => {
            return v.value == val
          })
          this.form.greenTypeName = arr[0].label

        }
      } else {
        this.form.greenTypeName = ""
      }
    },
    // 获取车系组
    getSeriesGroup(obj) {
      getSeriesGroupList(obj).then((res) => {
        this.seriesGroupList = res.map((v) => {
          if (typeof v.id === 'number') {
            v.id == `${v.id}`
          }
          return v
        })
      })
    },
    // 选择车系组
    changeSeriesGroup(val) {
      if (val) {
        if (this.seriesGroupList.length > 0) {
          let arr = this.seriesGroupList.filter(v => {
            return v.id == val
          })
          this.form.seriesGroupName = arr[0].seriesGroupName

        }
      } else {
        this.form.seriesGroupName = ""
      }
      this.$forceUpdate();
    },
    // 品牌名称组
    getBrandNames() {
      getBrandName({brandName: ""}).then(res => {
        this.getBrandNameList = res || []
      })
    },
    changeBrand(id) {
      if (id) {
        this.seriesGroupList = []

        this.getSeriesNameList = []
        this.form.seriesId = ""
        this.form.seriesName = ""

        this.form.modelName = ""
        this.form.seriesGroupId = ""
        this.form.seriesGroupName = ""
        if (this.getBrandNameList.length > 0) {
          let arr = this.getBrandNameList.filter(v => {
            return v.id == id
          })
          this.form.brandName = arr[0].name
          this.getSeriesGroup({brandName: this.form.brandName, carBrandId: id})
        }
        this.getSeriesNames(id)


      } else {
        this.form.seriesGroupId = ""
        this.form.seriesGroupName = ""
        this.form.brandName = ""
        this.form.seriesId = ""
        this.form.seriesName = ""

        this.form.modelName = ""

        this.getSeriesNameList = []
        this.seriesGroupList = []
      }

    },
    // 根据品牌id查询车系名称组
    getSeriesNames(id) {
      getSeriesName(id).then(res => {

        this.getSeriesNameList = res || []


      })
    },
    changeSeries(id) {
      if (id) {

        this.form.modelName = ""
        if (this.getSeriesNameList.length > 0) {
          let arr = this.getSeriesNameList.filter(v => {
            return v.id == id
          })
          this.form.seriesName = arr[0].name
        }
        // this.getModelNames(id)


      } else {

        this.form.seriesId = ""
        this.form.seriesName = ""

        this.form.modelName = ""
      }

    },
    // // 根据车系名称组查车型
    // getModelNames(id) {
    //   getModelName(id).then(res => {

    //     this.getModelNameList = res || []

    //   })
    // },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: "",
        brandId: "",
        brandName: "",
        seriesName: "",
        seriesId: "",

        modelName: "",
        shortName: "",
        seriesGroupName: "",
        seriesGroupId: "",
        carSeriesGroupId: "",
        price: "",
        year: "",
        makerId: "",
        makerName: "",

        // 车辆信息
        liter: "",
        dischargeStandard: "",
        fuelTypeId: "",
        fuelTypeName: "",
        enginePower: "",
        enginePowerKw: "",
        isGreen: "",
        modelCode: "",
        driveName: "",
        driveType: "",
        modelStatus: "",
        gearType: "",
        gearName: "",
        greenTypeId: "",
        greenTypeName: "",
        marketDate: "",
        minRegYear: "",
        maxRegYear: "",
        stopMakeYear: "",
        intake: "",
        seatNumber: "",
        bodyType: "",
        doorNumber: "",
        carStruct: "",
        isParallel: "",
        priceAllowance: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        brandName: "",
        seriesName: "",
        modelName: "",
        styleModel: "",
        IS_AVAILABLE: "",
      }
      this.getList();
    },

    /** 新增操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isNew = true
      this.title = "新增";
      // this.$router.push({
      //   path: "/zcwh/vehicleModelDetails",
      //   query: {
      //     type:this.isNew
      //   }
      // })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isNew = true
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCarBasic(id).then(response => {

        this.loading = false;
        this.form = response.data;
        this.form.fuelTypeId = response.data?.fuelTypeId?.toString()
        this.form.greenTypeId = response.data?.greenTypeId?.toString()
        this.form.maxRegYear = response.data.maxRegYear + ""
        this.form.minRegYear = response.data.minRegYear + ''
        this.form.stopMakeYear = response.data.stopMakeYear + ''
        this.form.brandId = response.data?.carBrandId?.toString()
        this.form.seriesId = response.data?.carSeriesId?.toString()
        this.form.seriesGroupId = Number(response.data.carSeriesGroupId)

        this.getSeriesNames(this.form.brandId)


        this.getSeriesGroup({brandName: this.form.brandName, carBrandId: this.form.brandId})
        this.open = true;
        this.title = "编辑";


      });
      this.$forceUpdate();
    },
    viewOpen(row) {
      this.isNew = false
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCarBasic(id).then(res => {
        this.loading = false;
        this.form = res.data;
        this.open = true;
        this.title = "查看";
      });
    },
    handleAc(row, num) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否${num == 1 ? '启用' : '停用'}该车型？`).then(() => {
        this.loading = true;
        return updateCar({id: ids, isAvailable: num});
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("处理成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.carBrandId = this.form.brandId
          this.form.carSeriesId = this.form.seriesId
          this.form.carSeriesGroupId = this.form.seriesGroupId
          if (this.form.id) {
            updateCar(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            carBrandAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否删除该车型？').then(() => {
        this.loading = true;
        return delModel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/carBrand/export', {
        ...this.queryParams
      }, `车型列表_${new Date().getTime()}.xlsx`)
    },
    /** 导出模板操作 */
    handleExportT() {
      this.download('car/carBasic/importTemplate', {}, `车型列表模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>


<style lang="scss" scoped>
.form-dialog {
  ::v-deep .el-dialog__header {
    padding: 10px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .box-card {
    margin-bottom: 20px;

    .card-title {
      font-size: 16px;
      position: relative;
      margin-left: 8px;
      padding: 0;
    }

    .card-title::after {
      content: "";
      width: 4px;
      height: 18px;
      background-color: aqua;
      display: block;
      position: absolute;
      left: -12px;
      top: 2px;
    }
  }
}
</style>
